package com.niodata.dp.web;

import com.niodata.dp.web.module.task.LoggerHandler;
import com.niodata.dp.web.module.task.LoggerHandler.LoggerHandshakeInterceptor;
import org.eclipse.jetty.websocket.api.WebSocketBehavior;
import org.eclipse.jetty.websocket.api.WebSocketPolicy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.jetty.JettyRequestUpgradeStrategy;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

  @Autowired
  LoggerHandler loggerHandler;


  @Override
  public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {

    webSocketHandlerRegistry.addHandler(loggerHandler, "/task/logger")
          .addInterceptors(new LoggerHandshakeInterceptor()).setAllowedOrigins("*");
  }

  @Bean
  public DefaultHandshakeHandler handshakeHandler() {

    WebSocketPolicy policy = new WebSocketPolicy(WebSocketBehavior.SERVER);
    policy.setInputBufferSize(8192);
    policy.setIdleTimeout(1200000);
    return new DefaultHandshakeHandler(new JettyRequestUpgradeStrategy());
    //return new DefaultHandshakeHandler(
    //    new JettyRequestUpgradeStrategy(new WebSocketServerFactory(policy)));
  }

}

